// Thud - a dynamic object-oriented language
// Copyright (C) 2009,2010 David H. Hovemeyer <david.hovemeyer@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

/*
 * FileInputStream.cpp
 *
 *  Created on: Dec 14, 2009
 *      Author: dhovemey
 */

#include <cstring>
#include <cerrno>
#include "util/String.h"
#include "util/IOException.h"
#include "util/EOFException.h"
#include "util/FileInputStream.h"

FileInputStream::FileInputStream(const std::string &fileName)
	: m_in(fopen(fileName.c_str(), "rb"))
{
	if (!m_in) {
		std::wstring msg(L"Could not open ");
		msg += String::fromUtf8(fileName);
		msg += L": ";
		msg += String::fromUtf8(strerror(errno));
		throw IOException(msg);
	}
}

FileInputStream::~FileInputStream()
{
	if (m_in) {
		fclose(m_in);
	}
}

int FileInputStream::read()
{
	int c = fgetc(m_in);
	if (c < 0) {
		checkErr();
	}
	return c;
}

size_t FileInputStream::read(void *buf_, size_t n)
{
	char *buf = (char *) buf_;

	size_t numRead = 0;
	while (numRead < n) {
		size_t rc = fread(buf + numRead, 1, n - numRead, m_in);
		if (rc == 0) {
			// A zero-length read is acceptable as long as it doesn't
			// indicate an error, and we've read at least 1 byte of data.
			checkErr();
			if (numRead > 0 || atEOF()) {
				break;
			}
		}
		numRead += rc;
	}

	if (numRead == 0 && atEOF()) {
		throw EOFException(numRead);
	}

	return numRead;
}

bool FileInputStream::atEOF()
{
	return feof(m_in);
}

void FileInputStream::checkErr()
{
	if (ferror(m_in)) {
		throw IOException(String::fromUtf8(strerror(errno)));
	}
}
